//
//  RegisterViewController.m
//  ECO
//
//  Created by 谷银行 on 2019/9/23.
//  Copyright © 2019 谷银行. All rights reserved.
//

#import "RegisterViewController.h"
#import "RegisterView.h"
#import "DetailModel.h"
@interface RegisterViewController ()<RegisterViewDelegate,RCIMUserInfoDataSource>{
    Model *model;
}
@property(nonatomic , strong)NSMutableArray *Array;
@property(nonatomic , strong)RegisterView *RegView;
@end

@implementation RegisterViewController
- (NSMutableArray *)Array{
    if (!_Array) {
        _Array = [[NSMutableArray alloc]init];
    }
    return _Array;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    [self ReGiView];
}
- (void)ReGiView{
    _RegView = [[RegisterView alloc]init];
    _RegView.delegate = self;
    _RegView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.RegView];
    [_RegView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view);
        make.left.equalTo(self.view);
        make.right.equalTo(self.view);
        make.bottom.equalTo(self.view);
    }];
}
// 登录代理请求数据
- (void)RegisterViewClick:(NSString *)Phone pass:(NSString *)Password{
    if ([Phone isEqualToString:@""] || [Password isEqualToString:@""]) {
        NSLog(@"请输入账号和密码");
        [BRProgressHUD showErrorWithStatus:@"APP客服手机端:请输入账号"];
        [BRProgressHUD dismissWithDelay:1.25];
    }else{
        NSLog(@"%@ ++++++ %@",Phone,Password);
        NSDictionary *dic = @{
                            @"username":Phone,
                            @"password":Password
                            };
        [HttpsTool post:@"/v1/im/user/info" params:dic success:^(id response) {
            NSLog(@"%@",response);
            self->model = [Model yy_modelWithJSON:response];
            NSLog(@"+++++%@",self->model.msg);
            if (self->model.status == 200) {
                MainViewController *main = [MainViewController new];
                NSUserDefaults *User = [NSUserDefaults standardUserDefaults];
                [User setObject:self->model.data.ryToken forKey:@"rytoken"];// 融云token
                [User setObject:self->model.data.iconUrl forKey:@"iconUrl"];// 头像
                [User setObject:self->model.data.nickname forKey:@"nickname"];// 名字
                [User setObject:self->model.data.token forKey:@"token"];
                [User setObject:[NSString stringWithFormat:@"%ld",(long)self->model.data.kfId] forKey:@"kfId"];
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self RyRCIM];
                });
                [BRProgressHUD showErrorWithStatus:@"登录成功"];
                [BRProgressHUD dismissWithDelay:1.25];
                [self presentViewController:main animated:YES completion:nil];
                
            }else{
                [BRProgressHUD showErrorWithStatus:self->model.msg];
                [BRProgressHUD dismissWithDelay:1.25];
            }
        } failure:^(NSError *error) {
            NSLog(@"%@",error);
        }];
    }
    
}
- (void)RyRCIM{
    [[RCIM sharedRCIM]setUserInfoDataSource:self];
    NSUserDefaults *User = [NSUserDefaults standardUserDefaults];
    [[RCIM sharedRCIM] connectWithToken:[User objectForKey:@"rytoken"] success:^(NSString *userId) {
        RCUserInfo *user = [[RCUserInfo alloc]init];
        user.portraitUri = model.data.iconUrl;
        user.name = model.data.nickname;
        NSArray *conversationList = [[RCIMClient sharedRCIMClient]
                                     getConversationList:@[@(ConversationType_PRIVATE)]];
        for (RCConversation *conversation in conversationList) {
            NSLog(@"会话类型：%lu，目标会话ID：%@ , %@", (unsigned long)conversation.conversationType, conversation.targetId,conversation.lastestMessage.senderUserInfo.name);
               // 循环添加数组
            [self.Array addObject:conversation];
        }
        NSLog(@"登陆成功。当前登录的用户ID：%@", userId);
    } error:^(RCConnectErrorCode status) {
        NSLog(@"登陆的错误码为:%ld", (long)status);
    } tokenIncorrect:^{
        //token过期或者不正确。
        //如果设置了token有效期并且token过期，请重新请求您的服务器获取新的token
        //如果没有设置token有效期却提示token错误，请检查您客户端和服务器的appkey是否匹配，还有检查您获取token的流程。
        NSLog(@"token错误");
    }];
}
-(void)getUserInfoWithUserId:(NSString *)userId completion:(void (^)(RCUserInfo *))completion{
   RCUserInfo *user = [[RCUserInfo alloc]init];
    for (int i = 0; i<self.Array.count; i++) {
        RCConversation *conversation = self.Array[i];
        if ([userId isEqualToString:conversation.targetId]) {
            user.userId = conversation.targetId;// id
            NSDictionary *dic = @{
                                @"userId":conversation.targetId
                                };
            [HttpsTool get:@"/kf/eco/user/findUser" params:dic success:^(id response) {
                NSLog(@"获取用户信息及粉丝数 : %@",response);
                NSDictionary *dict = [[NSDictionary alloc]init];
                DetailModel *model = [DetailModel yy_modelWithJSON:response];
                dict = [model.data.user yy_modelToJSONObject];
                user.name = dict[@"userName"];
                user.portraitUri = dict[@"userImgUrl"];// 头像的url
                [[RCIM sharedRCIM]refreshUserInfoCache:user withUserId:userId];
                // 携带当前的
                [RCIM sharedRCIM].currentUserInfo = [[RCUserInfo alloc]initWithUserId:conversation.targetId name:dict[@"userName"] portrait:dict[@"userImgUrl"]];
            } failure:^(NSError *error) {
                NSLog(@"%@",error);
            }];
            
        }else{
        }
    }
    return completion(user);
}
@end
